package app.musicPlayer.domain;


import java.util.Date;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.auth.AccessToken;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.R;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import app.persistencia.ListasDeReproduccion;
import app.socialInteraction.FacebookIntegration;
import app.utils.Utiles;
import app.socialInteraction.*;
import app.socialInteraction.SessionEvents.AuthListener;


public class SocialMusicPlayerActivity extends Activity {

	private static final String CONSUMER_KEY = "MMi2IT8blORBjNRX8xg";
	private static final String CONSUMER_SECRET = "GG0oytZxlgCCL0JKWIDbmeBqW86N9CdTwBRFgkri8";
	private static final String ACCESS_TOKEN = "500547496-BIDvvcTrtbaJlZEZbJsuAacd4f5n07dBrktwbM0";
	private static final String TOKEN_SECRET = "qmQ0UgvuuENX6txvhiuyMQnqx84kYAtyl3OWa45QE4";
	private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
    private static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
    private static final String CALLBACK_URL = "socialmusic://twitter";
    private TextView codigoRespuesta;
    private Button botonAutorizar;
    private TextView campoTweet;
    private Button botonEnviarTweet;
    private ImageButton reproducer;
    OAuthConsumer consumer;
    OAuthProvider provider;
    AccessToken a;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menumain, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.acercaDe:
	        	mostrarAcerca();
	        	return true;
	        case R.id.ajustes:
	            ajustes(null);
	            return true;
	        case R.id.salir:
	        	salir();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void mostrarAcerca() {
		//Utiles.showEnProximasActualizaciones(SocialMusicPlayerActivity.this);
		
    	AlertDialog alertDialog = new AlertDialog.Builder(SocialMusicPlayerActivity.this).create();
    	alertDialog.setTitle("Acerca de");
    	alertDialog.setMessage("Esta aplicacion ha sido creada por:\n" +
    			"Joan Isaac Collado Navarro, Marc Fontbona Miralles y Ruben Ferre Baiges " +
    			"para la asignatura de Gestio Projecte de Software");
       // final UsuariosSQLiteHelper dbUsers = new UsuariosSQLiteHelper(this,"DBTasks", null, 1);
 	    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
 	    	public void onClick(DialogInterface dialog, int which) {
    	    } 
 	    });
     	alertDialog.show();
		//Utiles.showMessage(SocialMusicPlayerActivity.this, "Esto es una prueba");
    }
	
	private void salir() {
		AlertDialog alertDialog = new AlertDialog.Builder(SocialMusicPlayerActivity.this).create();
    	alertDialog.setTitle("Salir");
    	alertDialog.setMessage("�Estas seguro que deseas salir de la aplicacion?");
 	    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
 	    	public void onClick(DialogInterface dialog, int which) {
 	    		finish();
 	    	} 
    	});
     	alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
     		public void onClick(DialogInterface dialog, int which) {	  
     		} 
     	});
     	alertDialog.show();
	}
	
	private void tweet_message() {    
     // Cal fer l'autentificacio a twitter amb les 2 claus publiques que ens han donat
		System.out.println("A");
       consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
       provider = new CommonsHttpOAuthProvider(REQUEST_URL,ACCESS_URL,AUTHORIZE_URL);  
       String authUrl;
       System.out.println("B");
        try { 
            // Permet que la appi es conecti a twitter
        	authUrl = provider.retrieveRequestToken(consumer, "socialmusic://twitter");
        	System.out.println("C");
            // Utilitzem el intent per mostrar la finestra de login
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	@Override
    protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
        Uri uri = intent.getData();         
        System.out.println("asdfasdfasfasdfasdfasdfadsf");
        // Mirem si la url de la que tornem es correcte
        if (uri != null && uri.toString().startsWith("bibliovirt://twitter")) {
           // Agafem el pin code i creem les claus privades
           String pinCode = uri.getQueryParameter("oauth_verifier");
           try {
               provider.setOAuth10a(true);
               provider.retrieveAccessToken(consumer,pinCode);                                 
                String ACCES_KEY = consumer.getToken();
                String ACCES_SECRET = consumer.getTokenSecret();                
                a = new AccessToken(ACCES_KEY,ACCES_SECRET);
   //            botonEnviarTweet.setEnabled(true);
   //            botonAutorizar.setEnabled(false);
   //            botonAutorizar.setBackgroundResource(R.layout.blackbutton);
   //            botonEnviarTweet.setBackgroundResource(R.layout.bluebutton);
               Toast.makeText(this, "Loggin Successful!", Toast.LENGTH_SHORT).show();
           } catch (Exception e) {
               e.printStackTrace();
               Toast.makeText(this, "Connection error! Try Again!", Toast.LENGTH_SHORT).show();
           }
         }
    }
	
	private void init_tweet() {
        Thread t = new Thread(new Runnable() {        
           public void run() {
               // TODO Auto-generated method stub
               tweet_message();
           }
       }); 
       t.start();
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //ImageButton reproductor = (ImageButton)findViewById(R.id.reproductor);
		final CancionesSistema s = CancionesSistema.getIntances();
		
	    if (android.os.Build.VERSION.SDK_INT > 9) {
	          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	          StrictMode.setThreadPolicy(policy);
	    }
	    final TextView logTwit = (TextView)findViewById(R.id.logTwitter);
	    logTwit.setText("No logueado");
        ImageButton button1 = (ImageButton)findViewById(R.id.loginTwitter);
        button1.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		init_tweet();
        		logTwit.setText("Logueado");
        	}

        });
        	//reproducer.setVisibility(View.GONE);
        reproducer = (ImageButton)findViewById(R.id.reproductooor);
        reproducer.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		if(ReproduccionActual.getIntances().isEmpty())
        			Utiles.showMessage(SocialMusicPlayerActivity.this, "Aun no hay nada reproduciendo, pon algo a reproducir!!!");
        		else {
        		Intent intent = new Intent(SocialMusicPlayerActivity.this, Mp3player.class);
	            	finish();
	            	startActivity(intent);
        		}
        	}
        });

  

		
        ListasDeReproduccion listasDeReproduccion = ListasDeReproduccion.getIntances();
        listasDeReproduccion.importListas(SocialMusicPlayerActivity.this);
        
        /*reproductor.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
            	goToReproductor(null);
		    }
        });*/
        ImageButton artista = (ImageButton)findViewById(R.id.selecartista);
        artista.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		goToArtista(null);
        	}
        });
        ImageButton album = (ImageButton)findViewById(R.id.selecalbum);
        album.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		goToAlbum(null);
        	}
        });
        ImageButton gestionlistas = (ImageButton)findViewById(R.id.gestionlistas);
        gestionlistas.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		goToGestionListas(null);
        	}
        });
        ImageButton listas = (ImageButton)findViewById(R.id.listas);
        listas.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		goToListas(null);
        	}
        });    
        
        ImageButton configuracio = (ImageButton)findViewById(R.id.configuracio);
        configuracio.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		ajustes(null);
        	}
        });
        
        /**
         * FACEBOOK
         */
        if (FacebookIntegration.APP_ID == null) {
            Utiles.showMessage(this, "Facebook Applicaton ID must be "
                    + "specified before running this example: see FbAPIs.java");
            return;
        }
        mHandler = new Handler();

        mText = (TextView) SocialMusicPlayerActivity.this.findViewById(R.id.t);
        mUserPic = (ImageView) SocialMusicPlayerActivity.this.findViewById(R.id.user);
        mLoginButton = (LoginButton) findViewById(R.id.login);

        Utility.mFacebook = new Facebook(FacebookIntegration.APP_ID);
        Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
        
        if(!s.isLoaded()) {
			final ProgressDialog dialog = ProgressDialog.show(SocialMusicPlayerActivity.this, "", 
	                "Cargando canciones, espere por favor...", true);
	    		Thread t = new Thread() {
	    		public void run() {
	    			s.setSongs(Utiles.giveMp3Files());
	    	    	dialog.dismiss();
	    	        TextView numero = (TextView) SocialMusicPlayerActivity.this.findViewById(R.id.numero);
	    	        int number = s.getTodasLasCanciones().size();
	    	        numero.setText("Actualmente tienes "+ number+ "  cancion(es) en tu dispositivo");

	    		}
	    	};
		
	    	t.start();
        }
     // restore session if one exists
        if(Utiles.getFacebook(SocialMusicPlayerActivity.this))
        {	
        	SessionStore.restore(Utility.mFacebook, this);
        }
        SessionEvents.addAuthListener(new FbAPIsAuthListener());
    	SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
        mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);
        if (Utility.mFacebook.isSessionValid()) {
            requestUserData();
        }

    }
    public void onResume() {
        super.onResume();
        if(Utility.mFacebook != null) {
            if (!Utility.mFacebook.isSessionValid()) {
                mText.setText("You are logged out! ");
                mUserPic.setImageBitmap(null);
            } else {
                Utility.mFacebook.extendAccessTokenIfNeeded(this, null);
            }
        }
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        /*
         * if this is the activity result from authorization flow, do a call
         * back to authorizeCallback Source Tag: login_tag
         */
            case AUTHORIZE_ACTIVITY_RESULT_CODE: {
                Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
                break;
            }
        }
    }
    String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins"};
    final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
    final static int PICK_EXISTING_PHOTO_RESULT_CODE = 1;
    private TextView mText;
    private ImageView mUserPic;
    private LoginButton mLoginButton;
    /**
     * FIN FACEBOOK
     */
    
    
    /*private void identificarse(Bundle b) {
		Intent intent = new Intent(SocialMusicPlayerActivity.this,
				TokenAccesoOAuth.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);	
	}*/
    
    
    
	private void goToReproductor(Bundle b) {
		Intent intent = new Intent(SocialMusicPlayerActivity.this,
				Mp3player.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);	
    }
	
    private void goToArtista(Bundle b) {
      	Intent intent = new Intent(SocialMusicPlayerActivity.this, 
      			SelectFromArtist.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);
    }
    
    private void goToAlbum(Bundle b) {
      	Intent intent = new Intent(SocialMusicPlayerActivity.this, SelectFromAlbum.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);
    }
    
    private void goToGestionListas(Bundle b) {
    	b = new Bundle();
    	b.putString(Utiles.FACTORDESELECCION, String.valueOf(Utiles.NON_SELECT));
    	b.putString(Utiles.VALOR, " ");
      	Intent intent = new Intent(SocialMusicPlayerActivity.this, AllSongs.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	//finish();
    	startActivity(intent);
    }
    
    private void goToListas(Bundle b) {
    	Intent intent = new Intent(SocialMusicPlayerActivity.this, ViewLists.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);
    }

    private void ajustes(Bundle b) {
		Intent intent = new Intent(SocialMusicPlayerActivity.this,
				Ajustes.class);
    	if(b != null) {
    		intent.putExtras(b);
    	}
    	finish();
    	startActivity(intent);	
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch(keyCode){
			case KeyEvent.KEYCODE_BACK:
				return false;
		}
		return super.onKeyDown(keyCode, event);
	}
    
    /**
     * FACEBOOK
     */
	public class FbAPIsAuthListener implements AuthListener {

        
        public void onAuthSucceed() {
            requestUserData();
        }

        
        public void onAuthFail(String error) {
            mText.setText("Login Failed: " + error);
        }
    }
   public void requestUserData() {
	    mText.setText("Fetching user name, profile pic...");
        Bundle params = new Bundle();
        params.putString("fields", "name, picture");
        Utility.mAsyncRunner.request("me", params, new UserRequestListener());
    }
   private Handler mHandler;

   public class UserRequestListener extends BaseRequestListener {

       
       public void onComplete(final String response, final Object state) {
           JSONObject jsonObject;
           try {
               jsonObject = new JSONObject(response);

               final String picURL = jsonObject.getString("picture");
               final String name = jsonObject.getString("name");
               Utility.userUID = jsonObject.getString("id");

               mHandler.post(new Runnable() {
                   
                   public void run() {
                       mText.setText("Welcome " + name + "!");
                       mUserPic.setImageBitmap(Utility.getBitmap(picURL));
                       mLoginButton.setImageResource(R.drawable.logout_button);
                   }
               });

           } catch (JSONException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }

   }
   public class FbAPIsLogoutListener implements SessionEvents.LogoutListener {
       
       public void onLogoutBegin() {
           mText.setText("Logging out...");
           Utiles.setFacebook(SocialMusicPlayerActivity.this, false);
       }

       
       public void onLogoutFinish() {
           mText.setText("You have logged out! ");
           mUserPic.setImageBitmap(null);
       }
   }
   public class AppRequestsListener extends BaseDialogListener {
       
       public void onComplete(Bundle values) {
           Toast toast = Toast.makeText(getApplicationContext(), "App request sent",
                   Toast.LENGTH_SHORT);
           toast.show();
       }

       
       public void onFacebookError(FacebookError error) {
           Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
                   Toast.LENGTH_SHORT).show();
       }

       
       public void onCancel() {
           Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled",
                   Toast.LENGTH_SHORT);
           toast.show();
       }
   }
   public class FQLRequestListener extends BaseRequestListener {

       
       public void onComplete(final String response, final Object state) {
           mHandler.post(new Runnable() {
               
               public void run() {
                   Toast.makeText(getApplicationContext(), "Response: " + response,
                           Toast.LENGTH_LONG).show();
               }
           });
       }

       public void onFacebookError(FacebookError error) {
           Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
                   Toast.LENGTH_LONG).show();
       }
   }

}